package leetcode;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @program: datastructureandalogorithm
 * @description:
 * @author: hmx
 * @create: 2022-01-29 17:38
 **/
public class LeetCode1765 {

    static final int[][] DIRS = new int[][]{{0, 1}, {0, -1}, {1, 0}, {-1, 0}};

    public int[][] highestPeak(int[][] isWater) {
        int m = isWater.length;
        int n = isWater[0].length;
        Queue<int[]> q = new LinkedList<>();
        boolean[][] visited = new boolean[m][n];
        for (int i = 0; i < m; i++) {
            for (int j = 0; j < n; ++j) {
                if (isWater[i][j] == 0) {
                    visited[i][j] = true;
                    q.offer(new int[]{i, j});
                }
            }
        }

        int[][] height = new int[m][n];
        while (!q.isEmpty()) {
            int size = q.size();
            for (int i = 0; i < size; i++) {
                int[] poll = q.poll();
                int x = poll[0];
                int y = poll[1];
                for (int[] dir : DIRS) {
                    int newX = x + dir[0];
                    int newY = y + dir[1];
                    if (newX >= 0 && newX < m && newY >= 0 && newY < n && !visited[newX][newY]) {
                        visited[newX][newY] = true;
                        height[newX][newY] = height[x][y] + 1;
                        q.offer(new int[]{newX, newY});
                    }
                }
            }
        }

        return height;
    }

}
